package com.smartleanx.module.hrm.service.esign.auth;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.smartleanx.module.hrm.service.esign.temp.vo.Auth.EsignProperties;
import com.smartleanx.module.hrm.service.examine.util.exception.EsignException;
import com.smartleanx.module.hrm.util.esign.EsignHttpHelper;
import com.smartleanx.module.hrm.util.esign.EsignHttpResponse;
import com.smartleanx.module.hrm.util.esign.enums.EsignRequestType;


import java.util.Map;

/**
 * E签宝标准请求
 * 
 * @author yanglihao
 */
public class EsignCommonService {

    public <T> T baseRequest(EsignProperties props, EsignRequestType reqType, String apiAddr, Object param,
                             Class<T> respClass) throws EsignException {
        String jsonParam = param != null ? JSONObject.toJSONString(param) : null;
        // 生成签名鉴权方式的header
        Map<String, String> header = EsignHttpHelper.signAndBuildSignAndJsonHeader(props.getAppId(),
            props.getAppSecret(), jsonParam, reqType.name(), apiAddr, props.isDebug());
        // 发起接口请求
        EsignHttpResponse httpResponse =
            EsignHttpHelper.doCommHttp(props.getHost(), apiAddr, reqType, jsonParam, header, props.isDebug());
        // 处理相应数据并返回
        JSONObject responseBody = JSONObject.parseObject(httpResponse.getBody(), JSONObject.class);
        int code = responseBody.getIntValue("code");
        if (code != 0) {
            throw new EsignException(responseBody.getString("message"));
        }
        return JSON.to(respClass, responseBody.getJSONObject("data"));
    }
}
